<?php

namespace app\user\logic;

use app\common\exception\LogicException;
use app\common\logic\EncryptLogic;
use app\model\User;
use app\model\UserToken;

class AuthLogic
{
    /**
     * @Description 登录
     * @author: zj
     * @param string $phone
     * @param string $password
     * @time 2023/08/29 10:04:33
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login (string $phone,string $password)
    {
        $userModel = new User();
        $info = $userModel
            ->field("id,name,phone,password,salt,status")
            ->where('phone',$phone)
            ->where('delete_time',$userModel::IS_DELETE_NO)
            ->where('status',$userModel::STATUS_ENABLE)
            ->find();
        if (!$info) {
            throw new LogicException("账号密码不匹配");
        }
        // 验证密码是否正确
        $this->checkPassword($password,$info['password'],$info['salt']);

        // 创建token
        $token = $this->createToken($info['name']);

        // 把用户数据存到缓存
        $tokenData = [
            'token' => $token,
            'user_info' => [
                'user_id' => $info['id'],
                'name' => $info['name'],
                'factory_id' => 0,
                'user_factory_id' => 0,
                'factory' => '',
            ]
        ];

        // 保存token值
        $userTokenModel = new UserToken();
        $oldTokenInfo = $userTokenModel
            ->where('user_id',$info['id'])
            ->field('id,token')
            ->find();
        if ($oldTokenInfo) {
            $userTokenModel->updateToke($oldTokenInfo['id'],$token);
            // 删除旧token缓存数据
            cache()->delete($oldTokenInfo['token']);
        } else {
            $userTokenModel->addToken($info['id'],$token);
        }

        $this->setCache($token,$tokenData['user_info']);

        return [
            'data' => $tokenData
        ];
    }

    /**
     * @Description 验证密码是否正确
     * @author: zj
     * @param string $password
     * @param string $passwordsMD5
     * @param string $salt
     * @time 2023/08/28 18:16:18
     * @return true
     */
    public function checkPassword(string $password,string $passwordsMD5,string $salt)
    {
        $encrypt = new EncryptLogic();
        $encryptPassword = $encrypt->encryptMD5($password,$salt);
        if ($encryptPassword != $passwordsMD5) {
            throw new LogicException("账号密码不匹配");
        }
        return true;
    }

    /**
     * @Description 创建token
     * @author: zj
     * @param string $name
     * @time 2023/08/28 18:18:54
     * @return string
     */
    public function createToken(string $name)
    {
        return md5($name.request()->time());
    }

    /**
     * @Description 设置缓存
     * @author: zj
     * @param string $token
     * @param array $userInfo
     * @time 2023/08/29 10:02:25
     * @return true
     */
    public function setCache(string $token,array $userInfo)
    {
        cache()->set('user_'.$token,json_encode($userInfo,JSON_UNESCAPED_UNICODE),86400);

        return true;
    }

    /**
     * @Description 退出登录
     * @author: zj
     * @param string $token
     * @param int $userId
     * @time 2023/08/29 10:03:43
     * @return true
     */
    public function logout(string $token,int $userId)
    {
        cache()->delete('user_'.$token);

        return true;
    }
}